package cn.pomelo.signal.common;

import cn.pomelo.signal.config.SignalConfig;
import cn.pomelo.signal.model.Trade;
import cn.pomelo.signal.service.TradeService;
import com.csvreader.CsvWriter;
import com.mysql.cj.jdbc.ClientPreparedStatement;
import com.mysql.cj.jdbc.JdbcStatement;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

@Component
public class CSVFileUtil {

    @Resource
    private TradeService tradeService;

    /**
     * 将所有txt文件转换成csv文件，然后通过数据库读取csv文件写入数据库
     */
    public static void readToCSV() throws IOException {
        System.out.println("转化成csv文件中...");
        File file = new File(SignalConfig.getData());
        File target = new File(SignalConfig.getTarget());
        // 目标文件所在的文件如果不存在就创建
        if (!target.getParentFile().exists()) {
            boolean b = target.getParentFile().mkdirs();
            if (!b) throw new FileNotFoundException();
        }
        CsvWriter csvWriter = new CsvWriter(SignalConfig.getTarget(), ',', StandardCharsets.UTF_8);
        File[] files = file.listFiles(f -> f.getName().endsWith(".txt"));
        for (File f : Objects.requireNonNull(files)) {
            // txt文本是ANSI编码
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "GBK"));
            String s = reader.readLine();
            // 获取股票代码及名称
            String[] strings = {s.substring(0, 6), s.substring(6, s.indexOf("日线")).replace(" ", "")};
            s = reader.readLine(); // 跳过第二行
            while (!SignalConfig.getEnd().equals((s = reader.readLine()))) {
                // 将代码以及名称加入每一行数据
                List<String> l = new ArrayList<>(Arrays.asList(strings));
                // 按照分隔符分割
                String[] split = s.split(SignalConfig.getSep());
                l.addAll(Arrays.asList(split));
                csvWriter.writeRecord(l.toArray(split));
            }
            reader.close();
        }
        csvWriter.close();
    }

    /**
     * 将csv文件读到数据库
     *
     * @param target 目标csv文件目录
     */
    public static void readToDataSource(String target) {
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://124.221.21.212/signal?allowLoadLocalInfile=true", "signal", "signal");
            String sql = "LOAD DATA LOCAL INFILE '" + target + "' IGNORE INTO TABLE trade FIELDS TERMINATED BY ',' ";
            statement = connection.prepareStatement(sql);
            System.out.println(sql);
            if (statement.isWrapperFor(JdbcStatement.class)) {
                ClientPreparedStatement mysqlStatement = statement.unwrap(ClientPreparedStatement.class);
                mysqlStatement.executeUpdate();
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 将最新数据读到数据库
     *
     * @param latest 最新数据的位置
     */
    public static List<Trade> readLatestData(String latest) throws IOException {
        String now = new SimpleDateFormat("yyyyMMdd").format(new Date());
        latest = latest + now + SignalConfig.getSuffix();
        File file = new File(latest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), SignalConfig.getCharset()));
        String line = reader.readLine();
        String[] strings = line.split(SignalConfig.getSep());
        List<Trade> trades = new ArrayList<>();
        while (!SignalConfig.getEnd().equals((line = reader.readLine()))) {
            strings = line.split(SignalConfig.getSep());
            Trade trade = new Trade();
            trade.setCode(strings[0]);
            trade.setName(strings[1].replace(" ", ""));
            LocalDate localDate = LocalDate.now();
            Instant instant = localDate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant();
            trade.setDate(Date.from(instant));
            trade.setOpen(Double.valueOf("0".equals(strings[7]) ? "0" : strings[11]));
            trade.setHighest(Double.valueOf("0".equals(strings[7]) ? "0" : strings[12]));
            trade.setLowest(Double.valueOf("0".equals(strings[7]) ? "0" : strings[13]));
            trade.setClose(Double.valueOf("0".equals(strings[7]) ? "0" : strings[14]));
            trade.setTraded(Long.valueOf("0".equals(strings[7]) ? "0" : strings[7]));
            trade.setTransaction(Double.valueOf("0".equals(strings[7]) ? "0" : strings[16]));
            if (trade.getTraded() != 0) {
                trades.add(trade);
            }
        }
        System.out.println(trades.size());
        return trades;
    }


}
